# -*- coding: utf-8 -*-
# @Time    : 2020/12/14 14:04
# @Author  : Guo_Zhanyu
# @File    : OmegaGo.py
from BoardBasics import *
from aiGzy2 import *
from PyQt5.QtCore import QTimer
import Choose
import requests
import datetime


class BoardClient(BoardGUI):
    def __init__(self, lines):
        super(BoardClient, self).__init__(lines)
        self.who_am_i = None
        self.Choose = QMainWindow()
        self.ChooseUI = Choose.Ui_MainWindow()
        self.ChooseUI.setupUi(self.Choose)
        self.ChooseUI.pushButton.clicked.connect(self.chooseBlack)
        self.ChooseUI.pushButton_2.clicked.connect(self.chooseWhite)
        self.Choose.show()

        # 获取的数据
        self.board_dict_get = dict()

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.operate)

        self.MainWindowUI.pushButton_2.clicked.connect(self.setPlayerMode)
        self.MainWindowUI.pushButton_3.clicked.connect(self.setAIMode)

        self.mode = 0
        self.ai = None
        pass

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            if self.board.winner is None and self.board.cur_runner.name == self.who_am_i.name and self.mode == 0:
                mouse_pos = [event.pos().x(), event.pos().y()]
                click_point = self.getClickPoint(mouse_pos)
                if click_point is not None:
                    if self.board.canDrop(click_point):
                        self.board.drop(self.board.cur_runner, click_point)
                        self.board.cur_runner = self.board.getNextRunner(self.board.cur_runner)
                        self.board.last = click_point
                        self.postBoardDictOnline(click_point.x, click_point.y)
                        pass
                    pass
                else:
                    print('超过棋盘范围...')
                    pass
                self.update()
                pass
            pass
        elif event.button() == Qt.RightButton:
            if self.board.winner is not None:
                self.board = Board(self._lines)
                self.postBoardDictOnline(-1, -1)
                self.update()
                pass
            pass
        pass

    def rerun(self):
        self.board = Board(self._lines)
        self.postBoardDictOnline(-1, -1)
        pass

    def closeEvent(self, event):
        self.board = Board(self._lines)
        self.postBoardDictOnline(-1, -1)
        pass

    def setPlayerMode(self):
        self.mode = 0
        pass

    def setAIMode(self):
        self.mode = 1
        pass

    def buttonFunc(self, ui):
        dataIn = ui.lineEdit.text()
        if dataIn != '':
            self.url = f'http://{dataIn}:5000/'
            pass
        ui.label_3.setText(self.url)
        self.timer.start(100)
        pass

    def chooseBlack(self):
        self.who_am_i = BLACK_CHESSMAN
        self.ai = AI(self._lines, self.who_am_i)
        self.show()
        self.Choose.close()
        pass

    def chooseWhite(self):
        self.who_am_i = WHITE_CHESSMAN
        self.ai = AI(self._lines, self.who_am_i)
        self.show()
        self.Choose.close()
        pass

    def operate(self):
        try:
            self.getBoardDictOnline()
            self.board.setBoard(self.board_dict_get['board'])
            self.ai.setBoard(self.board_dict_get['board'])
            runner = self.board_dict_get['runner']
            win = self.board_dict_get['win']
            new_last = Point(self.board_dict_get['lastX'], self.board_dict_get['lastY'])
            if new_last.x != -1 and new_last.y != -1:
                self.board.last = new_last
                pass

            if runner == 'black':
                self.board.cur_runner = BLACK_CHESSMAN
            elif runner == 'white':
                self.board.cur_runner = WHITE_CHESSMAN
                pass

            if win == 1:
                self.board.winner = BLACK_CHESSMAN
            elif win == 2:
                self.board.winner = WHITE_CHESSMAN
            else:
                self.board.winner = None
                pass

            self.update()
            if self.mode == 1 and self.board.cur_runner.name == self.who_am_i.name and self.board.winner is None:
                AI_point = self.ai.AI_drop()
                self.board.drop(self.who_am_i, AI_point)
                self.board.cur_runner = self.board.getNextRunner(self.board.cur_runner)
                self.board.last = AI_point
                self.postBoardDictOnline(AI_point.x, AI_point.y)
                self.update()
                pass
        except Exception as e:
            self.MainWindowUI.label_3.setText('连接失败...')
            print(e)
            self.timer.stop()
        pass

    def getBoardDictOnline(self):
        r1 = requests.get(self.url + 'board')
        self.board_dict_get = eval(r1.text)
        pass

    def postBoardDictOnline(self, x, y):
        board_dict_post = dict()
        board_dict_post['x'] = x
        board_dict_post['y'] = y

        r3 = requests.post(self.url + 'board', data=board_dict_post)
        print(str(datetime.datetime.now().strftime('%H:%M:%S')) + r3.text)
        pass

    pass


def main():
    client = QApplication(sys.argv)
    board_client = BoardClient(LINES)
    sys.exit(client.exec_())
    pass


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print(e)
        pass
    pass
